package dataProces;

import java.io.*;
import java.nio.charset.StandardCharsets;
import java.text.SimpleDateFormat;
import java.util.Date;
import javax.swing.JOptionPane;

public class FileOperations {
    private String path;

    public void exportTxt(String[] items, String[] data) {
        path = "data/BankData.txt";
        try {
            File file = new File(path);
            if (!file.exists()) {
                file.createNewFile();
            }
            OutputStreamWriter oWriter = new OutputStreamWriter(new FileOutputStream(file), StandardCharsets.UTF_8);
            for (int i = 0; i < data.length; i++)
                oWriter.write(items[i] + ':' + data[i] + "\r\n");
            oWriter.close();
            JOptionPane.showMessageDialog(null, "文件已导出至" + path, "提示", JOptionPane.ERROR_MESSAGE);
            logFile("导出账户信息至" + path);
        } catch (IOException e) {
            logFile("账户信息导出:" + e.getMessage());
            JOptionPane.showMessageDialog(null, "文件导出失败！", "错误", JOptionPane.ERROR_MESSAGE);
        }

    }

    public void logFile(String data) {
        SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd");
        Date date = new Date(System.currentTimeMillis());
        path = "log/BankSystem-log-" + formatter.format(date) + ".dat";
        formatter = new SimpleDateFormat("HH:mm:ss z");
        try {
            File file = new File(path);
            FileOutputStream fos;
            if (!file.exists()) {
                file.createNewFile();
                fos = new FileOutputStream(file);
            } else {
                fos = new FileOutputStream(file, true);
            }
            OutputStreamWriter osw = new OutputStreamWriter(fos, StandardCharsets.UTF_8);
            osw.write(formatter.format(date) + ':' + data + "\r\n");
            osw.close();
        } catch (Exception e) {
            System.out.println("日志模块:" + e.getMessage());
        }
    }
}
